<template>
	<a-select
		v-model:value="columnId"
		style="width: 100%"
		allow-clear
		placeholder="选择栏区"
		:options="options"
		@change="handleChange"
		:disabled="columnDisable"
	></a-select>
</template>

<script setup="colunmSelectByBarn">
	import BizColumnApi from "@/api/column/bizColumnApi";

	const columnDisable = ref(true);
	const emit = defineEmits(['update:columnId', 'update:columnName','init:columnId']);
	const columnId = ref();
	const listData = ref([]);
	const options = ref([]);

	onMounted(() =>{
		emit('init:columnId');
	})

	const selectByBarnId = (id) =>{
		const data = {
			barnId : id,
		}
		BizColumnApi.getListByBarnId(data)
			.then(resp =>{
				listData.value = resp;
				mapDataToOptions();
			})
			.catch(resp =>{
				console.error(resp);
			});
	};

	const mapDataToOptions = () => {
		options.value = listData.value.map(item => ({
			value: item.id,
			label: item.name,
		}));
	};

	const handleChange = (value) =>{
		if(value === undefined){
			emit('update:columnId', undefined);
			emit('update:columnName', undefined);
		}
		const selectedColumnId = value;
		const selectedColumn = listData.value.find(column => column.id === selectedColumnId);
		const selectedColumnName = selectedColumn ? selectedColumn.name : '';
		// 触发自定义事件
		if (selectedColumnId) {
			emit('update:columnId', selectedColumnId);
		}
		if (selectedColumnName) {
			emit('update:columnName', selectedColumnName);
		}
	}

	const initColumnName = (id) =>{
		columnId.value = id;
	}

	defineExpose({
		selectByBarnId,
		columnDisable,
		columnId,
		initColumnName,
	})
</script>

<style scoped>

</style>
